# fund DAO service
# Compare this snippet from app\service\dao_service\fund_service.py:
import time

from app.dao.fund_dao import Fund_DAO
from app.utils.config_reader import ConfigReader
from crawler.base_crawler import get_all_funds, get_paged_funds
from crawler.zhishucrawler import get_index as get_index_from_crawler


def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return get_instance


@singleton
class Fund_Service:
    def __init__(self):
        self.fund_dao = Fund_DAO()
        # 当前时间戳
        self.funds = ['0'] * 12250
        self.funds_updated_time = [[] * 12250]
        self.current_time = 0

    # def get_
    def get_funds(self, page, size):
        print(len(self.funds))

        print(len(self.funds))

        # 15分钟更新一次
        # 15分钟更新一次
        for i in range((int(page) - 1) * int(size), int(page) * int(size)):
            print(i)
            print(self.funds[i])
            if self.funds[i] == '0' or time.time() - self.current_time > 900:
                # to int
                page=int(page)
                size=int(size)

                result = get_paged_funds(int(page*size/50)+1)
                for j in range(len(result)):
                    self.funds[(int(page) - 1) * int(size) + j] = result[j]
                self.current_time = time.time()
                break
        print(self.current_time)

        return self.funds[(int(page) - 1) * int(size):int(page) * int(size)]

    def get_detail(self, fund_code):
        return self.fund_dao.get_fund_info(fund_code)

    def get_index(self):
        return get_index_from_crawler()


# test
if __name__ == "__main__":
    config_reader = ConfigReader()
    database_host = config_reader.get_value('database_dev', 'host')
    database_port = config_reader.get_int_value('database_dev', 'port')
    print(database_host)
    print(database_port)
